import axios from 'axios'
import config from '@/config/config'
import {getToken, removeToken, removeUser} from "@/utils/auth";
import {Notification, MessageBox, Message} from 'element-ui'
import router from '@/router'

// 创建 axios 实例
const request = axios.create({
    // API 请求的默认前缀
    baseURL: config.BASE_API_URL,

    // 请求超时时间
    timeout: 20000,


})

/**
 * 异常拦截处理器
 *
 * @param {*} error
 */
const errorHandler = error => {
    // 判断是否是响应错误信息
    if (error.response) {
        if (error.response.status == 401) {
            removeAll()
            location.reload()
        } else {
            Notification({
                message: '网络异常,请稍后再试...',
                position: 'top-right',
            })
        }
    }

    return Promise.reject(error)
}

request.interceptors.request.use(config => {
    //是否需要设置token
    const isToken = (config.headers || {}).isToken === false
    if (getToken() && !isToken) {
        //每个请求携带自定义token
        config.headers['Authorization'] = getToken()
    }
    // get请求映射params参数
    if (config.method === 'get' && config.params) {
        let url = config.url + '?';
        for (const propName of Object.keys(config.params)) {
            const value = config.params[propName];
            var part = encodeURIComponent(propName) + "=";
            if (value !== null && typeof (value) !== "undefined") {
                if (typeof value === 'object') {
                    for (const key of Object.keys(value)) {
                        let params = propName + '[' + key + ']';
                        var subPart = encodeURIComponent(params) + "=";
                        url += subPart + encodeURIComponent(value[key]) + "&";
                    }
                } else {
                    url += part + encodeURIComponent(value) + "&";
                }
            }
        }
        url = url.slice(0, -1);
        config.params = {};
        config.url = url;
    }
    return config
}, error => {
    Promise.reject(error)
})


request.interceptors.response.use(res => {
        const code = res.data.code;
        const msg = res.data.msg;
        const data = res.data.data;
        if (code === 401) {
            MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
                confirmButtonText: '重新登录',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                store.dispatch()
            })
        } else if (code === 500) {
            Notification.error({
                title: msg,
                message: data
            })
            return Promise.reject(new Error(msg))
        } else if (code !== 200) {
            Notification.error({
                title: msg
            })
            return Promise.reject('error')
        } else {
            return res.data
        }
    },
    error => {
        let {message} = error;
        if (message == "Network Error") {
            message = "后端接口连接异常";
        } else if (message.includes("timeout")) {
            message = "系统接口请求超时";
        } else if (message.includes("Request failed with status code")) {
            if (message.substr(message.length - 3) == 401) {
                message = 'token已过期，请重新登录'
                removeToken();
                removeUser();
                router.push('/login')
            } else {
            message = "系统接口" + message.substr(message.length - 3) + "异常";
            }
        }
        Message({
            message: message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)


/**
 * GET 请求
 */
export function get(url, params = {}) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params: params
        })
            .then(response => {
                resolve(response.data);
            })
            .catch(err => {
                reject(err)
            })
    })
}

/**
 * POST 请求
 */
export function post(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.post(url, data)
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err)
            })
    })
}

/**
 * 上传文件 POST 请求
 *
 * @param {String} url
 * @param {Object} data
 * @param {Object} options
 * @returns {Promise<any>}
 */
export const upload = (url, data = {}, options = {}) => {
    return request({
        url,
        method: 'post',
        data: data,
        ...options,
    })
}

export default request
